package com.my.zl.console.common.utils.generator;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.my.zl.console.common.utils.generator.bean.ZLColumn;
import com.my.zl.console.common.utils.generator.bean.ZLConfig;
import com.my.zl.console.common.utils.generator.bean.ZLTable;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component("textReader")
public class ReaderText implements ReaderData<ZLConfig> {
    
    private static Pattern SPLIT_RULE = Pattern.compile(" *: *");//拆分条件
    
    @Override
    public void parseData(ZLConfig configParam) throws Exception {
        // TODO Auto-generated method stub
        log.info("自定义对象文本加载方式");
        long start = System.currentTimeMillis();
        
        File file = new File(configParam.getSqlPath());
        
        List<ZLTable>  tableLists = new ArrayList<>();
        List<String> hasCodeList = new ArrayList<>();
        
        if(file.exists()){
            if(file.isDirectory()){
                File[] allFiles = file.listFiles();
                for(File f: allFiles){
                    if(f.isFile()){
                        readerEntry(configParam,tableLists,hasCodeList,f.getPath(),true);
                    }
                }
            }else{
                readerEntry(configParam,tableLists,hasCodeList,configParam.getSqlPath(),true);
            }
        }
        
        log.info("Data loading use time:" + (System.currentTimeMillis() - start) / 1000F + "s");
    }
    
    @Override
    public Map<String,Object> getData(ZLConfig configParam) throws Exception {
        long start = System.currentTimeMillis();
        
        Map<String,Object> result = new HashMap<>();
        
        List<ZLTable>  tableLists = new ArrayList<>();
        List<String> hasCodeList = new ArrayList<>();
        
        File file = new File(configParam.getSqlPath());
        if(file.exists()){
            if(file.isDirectory()){
                File[] allFiles = file.listFiles();
                for(File f: allFiles){
                    if(f.isFile()){
                        readerEntry(configParam,tableLists,hasCodeList,f.getPath(),false);
                    }
                }
            }else{
                readerEntry(configParam,tableLists,hasCodeList,configParam.getSqlPath(),false);
            }
        }
        result.put("tables", configParam.getTbls());
        
        log.info("Data loading use time:" + (System.currentTimeMillis() - start) / 1000F + "s");
        
        return result;
    }
    
    public static void readerEntry(ZLConfig configParam, List<ZLTable> tableLists,List<String> hasCodeList,String path,boolean tableFlag) throws Exception {
//        String str = "---T_user:用户:分组:注释: \n key1:字段1:VAR:10:Y:N:注释\n key2:字段2:VAR:10:注释:N:Y";
//        String[] txtList2 = str.split("\\n");
        try{
            List<String> txtList = FileUtil.readLines(path, CharsetUtil.CHARSET_UTF_8);
            
            Map<String,ZLTable> beanMap = new HashMap<>();//对象体
            String beanname  = null;
            for(String txtStr : txtList){
                if(txtStr.startsWith("---")){//对象的开始
                    txtStr = txtStr.substring(3).trim();
                    if(hasCodeList.contains(beanname)){
                        log.info("存在重复对象>>{}",beanname);
                        beanname = null;
                        break;
                    }
                    String[] arr =  SPLIT_RULE.split(txtStr);//T_user:用户:分组:注释
                    String tableCode = StrUtil.toUnderlineCase(arr[0].trim()).toLowerCase();
                    String addPrefixOverride = "";
                    if(StringUtils.isNotBlank(configParam.getAddPrefixOverride())){
                        addPrefixOverride = configParam.getAddPrefixOverride().trim().toLowerCase();
                        addPrefixOverride = addPrefixOverride.endsWith("_")?addPrefixOverride:addPrefixOverride+"_";
                    }
                    String tableCode2 = addPrefixOverride + tableCode;
                    log.info("表>>{} ", tableCode2);
                    
                    //如果有选中的表,则只生成选中的表,否则全部加载
                    List<String> selectedTables = configParam.getLoadTables();
                    String queryType = StringUtils.isNotBlank(configParam.getQueryType())?configParam.getQueryType():"0";
                    if(selectedTables != null && selectedTables.size()>0 
                            &&(("0".equals(queryType) && !selectedTables.stream().anyMatch(x-> x.equalsIgnoreCase(tableCode) || x.equalsIgnoreCase(tableCode2)))
                               || !selectedTables.stream().anyMatch(x-> tableCode.contains(x.toLowerCase()) || tableCode2.contains(x.toLowerCase())))){
                        continue;
                    }
                    beanname = tableCode2;
                    
                    ZLTable ctbl = new ZLTable();
                    ctbl.setTableName(tableCode2);
                    ctbl.setTableCode(tableCode2);
                    ctbl.setTableTitle(arr[1].trim());
                    ctbl.setTableTag(arr.length>2?arr[2].trim():null);
                    ctbl.setTableComment(arr.length>3?arr[3].trim():null);
                    ctbl.setAllcols(new ArrayList<>());
                    
                    beanMap.put(beanname, ctbl);
                    hasCodeList.add(beanname);
                }else if(StrUtil.isNotBlank(beanname)){
                    //后面紧跟的都为属性
                    String[] arr =  SPLIT_RULE.split(txtStr);//key1:字段1:VAR:10:Y:N:注释
                    List<ZLColumn> curbean = beanMap.get(beanname).getAllcols();
                    ZLColumn col = new ZLColumn();
                    col.setColumnName(StrUtil.toUnderlineCase(arr[0].trim()));
                    col.setColumnCode(StrUtil.toUnderlineCase(arr[0].trim()).toLowerCase());
                    col.setColumnTitle(arr[1].trim());
                    col.setColumnDatatype(arr.length>1?arr[2].trim():"String");
                    String columnLength = null;
                    String columnPrecision = null;
                    if(arr.length>3){
                        String[] larr = arr[3].split(",");
                        columnLength = StringUtils.isBlank(larr[0])?columnLength:larr[0];
                        columnPrecision = larr.length>1?larr[1]:null;
                    }
                    col.setColumnLength(columnLength);
                    col.setColumnPrecision(columnPrecision);
                    
                    col.setColumnPrimarykey(arr.length>4?("Y".equalsIgnoreCase(arr[4].trim())?"1":"0"):"0");
                    col.setColumnMandatory(arr.length>5?("Y".equalsIgnoreCase(arr[5].trim())?"1":"0"):"1");
                    col.setColumnComment(arr.length>6?arr[6]:null);
                    curbean.add(col);
                }
            }
        }catch(Exception e){
            log.error("Table loading error>>{},{}",path,e);
        }
    }
}
